/**
 *  列表页
 *
 * 作者 admin
 * 日期 2024-08-07 16:43:01
 */
layui.use(['jquery', 'laydate', 'febs', 'form', 'table', 'commonJS', 'validate'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        febs = layui.febs,
        form = layui.form,
        table = layui.table,
        commonJS = layui.commonJS,
        validate = layui.validate,
        // treeTable = layui.treeTable,
        $view = $('#febs-accidentReportSurvey'),
        $query = $view.find('#query'),
        $accidentType = $view.find('#accidentType'),
        $accidentLevel = $view.find('#accidentLevel'),
        $searchForm = $view.find('#accidentReportSurvey-table-form'),
        tableIns;

    form.verify(validate);
    initDictItemSelect_reportSurvey();
    initTable();
    // treeTableInit();
    initDate();
    form.render();


    function initDate() {
        //初始化日期控件
        laydate.render({
            elem: '#laydate-range',
            type: 'datetime',
            range: ['#start-date', '#end-date'],
        })
    }
    function initDictItemSelect_reportSurvey(){
        //事故类型
        febs.initDictItemSelect($accidentType,'SAFETY_ACCIDENT_TYPE','',null);
        //事故等级
        febs.initDictItemSelect($accidentLevel,'SAFETY_ACCIDENT_LEVEL','',null);
    }

    function initTable() {
        tableIns = febs.table.init({
            elem: $view.find('table'),
            id: 'accidentReportSurveyTable',
            url: ctx + 'accidentReport/recordList',
            where: getQueryParams(),
            skin: '',
            height: getTableHeight(),
            cols: [[
                {title: '序号', type: 'numbers',width: 60},
                {field: 'tenantName', title: '公司名称', minWidth: 260,hide:!hasHeadCompanyRole},
                {field: 'accidentNo',align:'center', title: '事故编号',event: 'detail', minWidth: 140,templet:function (d) {
                        return '<p style="color:#01aaed;cursor:pointer">'+d.accidentNo+'</p>'
                    }
                },
                {field: 'accidentTitle',align:'left', title: '事故名称', minWidth: 300},
                {field: 'accidentDate',align:'center', title: '发生时间', width: 160},
                {field: 'accidentPlace',align:'left', title: '发生地点', minWidth: 280},
                {field: 'accidentType',align:'center', title: '事故类型', width: 120,templet:function (d){
                        if(d.accidentType){
                            return febs.getDictLabel(accidentTypeList,d.accidentType)
                        }
                    }
                },
                {field: 'accidentLevel',align:'center', title: '事故等级', width: 200,templet:function (d){
                        if(d.accidentLevel){
                            return febs.getDictLabel(accidentLevelList,d.accidentLevel)
                        }
                    }
                },

                // {field: 'obligationDeptName',align:'center', title: '责任部门', minWidth: 140},
                // {field: 'obligationRealName',align:'center', title: '责任人', width: 120},
                {field: 'surveyStatus',align:'center', title: '调查状态', width: 100, templet: function (d) {
                        var flg = '';
                        switch (d.surveyStatus) {
                            case "1": {
                                flg = '<span class="layui-badge febs-bg-cyan">待指派</span>'
                                break;
                            }
                            case "2": {
                                flg = '<span class="layui-badge febs-bg-orange">待调查</span>'
                                break;
                            }
                            case "3": {
                                flg = '<span class="layui-badge febs-bg-purple">进行中</span>'
                                break;
                            }
                            case "4": {
                                flg = '<span class="layui-badge febs-bg-gold">待审核</span>'
                                break;
                            }
                            case "5": {
                                flg = '<span class="layui-badge febs-bg-red">审核退回</span>'
                                break;
                            }
                            case "6": {
                                flg = '<span class="layui-badge febs-bg-green">完成</span>'
                                break;
                            }
                        }
                        return flg;
                    }
                },
                {field: 'surveyDeadline',align:'center', title: '调查截止时间', width: 120},
                {field: 'accidentReason',align:'center', title: '事故原因', width: 140,templet:function (d){
                        if(d.accidentReason && d.accidentReason != '--'){
                            return febs.getDictLabel(reasonTypeList,d.accidentReason);
                        }else{
                            return '--';
                        }
                    }
                },
                // {field: 'directReason', align:'center', title: '直接原因', width: 160},
                // {field: 'indirectionReason',align:'center',  title: '间接原因', width: 160},
                // {field: 'rootReason',align:'center',  title: '根本原因', width: 160},
                {field: 'obligationDeptNameRectification',align:'center',  title: '整改部门', width: 120},
                {field: 'obligationRealNameRectification',align:'center',  title: '整改责任人', width: 120},
                {field: 'rectificationOpinion',align:'center',  title: '整改措施', minWidth: 180},
                {field: 'rectificationStatus',align:'center', title: '整改状态', width: 120, templet: function (d) {
                        var flg = '--';
                        switch (d.rectificationStatus) {
                            case "1": {
                                flg = '<span class="layui-badge febs-bg-cyan">待分派</span>'
                                break;
                            }case "2": {
                                flg = '<span class="layui-badge febs-bg-orange">待整改</span>'
                                break;
                            }
                            case "3": {
                                flg = '<span class="layui-badge febs-bg-red">审核退回</span>'
                                break;
                            }
                            case "4": {
                                flg = '<span class="layui-badge febs-bg-gold">待审核</span>'
                                break;
                            }
                            case "5": {
                                flg = '<span class="layui-badge febs-bg-green">完成</span>'
                                break;
                            }
                        }
                        return flg;
                    }
                },
                {field: 'rectificationDeadline',align:'center', title: '整改截止时间', width: 120, templet: function (d) {
                    if(!d.reportRectificationId){
                            return '--';
                        }else if(d.rectificationDeadline){
                            return d.rectificationDeadline;
                        }else{
                            return '';
                        }
                    }
                },
                {field: 'reportId', title: '事故id', hide:true},
                {field: 'reportRectificationId', title: '事故整改id', hide:true},
                {title: '操作', fixed:'right', toolbar: '#accidentReportSurvey-option', width: 160}
            ]],
            done: function (res, curr, count) {
                mergeColumn(res);
            },
        });
    }

    function mergeColumn(res) {
        //按字段 合并表格
        var data = res.data;
        if(commonJS.isEmpty(data)){
            return;
        }
        var mergeIndex = 0;//定位需要添加合并属性的行数
        var mark = 1; //这里涉及到简单的运算，mark是计算每次需要合并的格子数
        var columsName = ['tenantName','accidentNo','accidentTitle','accidentDate','accidentPlace','accidentType','accidentLevel','surveyStatus','surveyDeadline','accidentReason'];//需要合并的列名称
        var columsIndex = [1,2,3,4,5,6,7,8,9,10];//需要合并的列索引值
        for (var k = 0; k < columsName.length; k++) { //这里循环所有要合并的列
            var trArr = $view.find('.layui-table-body').find("tr");//所有行 最大问题出现在此处，获取不到表数据
            for (var i = 1; i < res.data.length; i++) { //这里循环表格当前的数据
                var reportId_before = data[i].reportId;
                var reportId_after = data[i-1].reportId;
                var tdCurArr = trArr.eq(i).find("td").eq(columsIndex[k]);//获取当前行的当前列
                var tdPreArr = trArr.eq(mergeIndex).find("td").eq(columsIndex[k]);//获取相同列的第一列
                if ((reportId_before+data[i][columsName[k]]) === (reportId_after+data[i - 1][columsName[k]]))  { //后一行的值与前一行的值做比较，相同就需要合并
                    mark += 1;
                    tdPreArr.each(function (index,item) {//相同列的第一列增加rowspan属性
                        if(index == 0){
                            $(this).attr("rowspan", mark);
                        }

                    });
                    tdCurArr.each(function (index,item) {//当前行隐藏
                        if(index == 0){
                            $(this).css("display", "none");
                        }
                    });
                } else {
                    mergeIndex = i;
                    mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
                }
            }
            mergeIndex = 0;
            mark = 1;

        }
    }

    //操作列点击事件
    table.on('tool(accidentReportSurveyTable)', function(obj){
        var data = obj.data; // 获取当前行数据
        var reportId = data.reportId;
        var tenantId = data.tenantId;
        var reportRectificationId = data.reportRectificationId;
        if(obj.event === 'detail'){
            febs.modal.open('事故上报详情', 'accidentReport/detail/'+reportId, {
                btn: ['关闭'],
                area: $(window).width() <= 750 ?  ['85%', '80%']: ['95%', '95%'],
                shadeClose:true,
                yes: function (index, layero) {
                    layer.closeAll();
                },
            });
        }else if (obj.event === 'survey-record') {
            febs.modal.open('调查结果录入', 'accidentReport/surveyRecord/'+reportId+'/null', {
                btn: ['保存','提交', '取消'],
                area: $(window).width() <= 750 ? ['85%', '80%']: ['95%', '95%'],
                yes: function (index, layero) {
                    $('#reportSurveyRecord-edit').find('#save').trigger('click');
                },
                btn2: function (index, layero) {
                    $('#reportSurveyRecord-edit').find('#submit').trigger('click');
                    return false;
                },
                btn3: function () {
                    layer.closeAll();
                },
                data: {
                    tenantId: tenantId,
                    reportId: reportId,
                }

            });
        }else if (obj.event === 'edit-record') {
            febs.modal.open('调查结果修改', 'accidentReport/surveyRecord/'+reportId+'/'+reportRectificationId, {
                btn: ['保存','提交', '取消'],
                area: $(window).width() <= 750 ? ['85%', '80%']: ['95%', '95%'],
                yes: function (index, layero) {
                    $('#reportSurveyRecord-edit').find('#save').trigger('click');
                },
                btn2: function (index, layero) {
                    $('#reportSurveyRecord-edit').find('#submit').trigger('click');
                    return false;
                },
                btn3: function () {
                    layer.closeAll();
                },
                data: {
                    tenantId: tenantId,
                    reportId: reportId,
                    reportRectificationId: reportRectificationId,
                }

            });
        }else if (obj.event === 'survey-audit-submit') {
            //提交调查审核
            febs.modal.confirm('提交审核','确定提交审核？', function (index) {
                febs.postArray(ctx + 'accidentReport/surveyRecordSubmit', data, function () {
                    layer.closeAll();
                    febs.alert.success('提交成功');
                    $('#febs-accidentReportSurvey').find('#query').trigger('click');
                });
            });
        }
    });

    form.on('select(leaderDeptSelect)', function(obj){
        // 获取选中项 value
        var data={
            deptId : obj.value
        }
        $("#leaderUserSelect").empty();
        febs.getSync(ctx + 'user/deptUserList', data, function (r) {
            var userList = r.data;
            var optionDefault = '<option value=""></option>';
            var options = '';
            $.each(userList,function (index,item) {
                var option =  '<option value="'+item.userId+'">'+item.uname+'</option>';
                options += option;
            })
            $("#leaderUserSelect").append(optionDefault+options);
        });
        form.render();
    });

    table.on('sort(accidentReportSurveyTable)', function (obj) {
        tableIns.reload({
            initSort: obj,
            where: $.extend(getQueryParams(), {
                field: obj.field,
                order: obj.type
            }),
            autoSort: true
        });
    });

    function reloadPage(curr) {
        var _curr = $view.find(".layui-laypage-em").next().html();
        if (!!curr) {
            _curr = curr;
        }
        tableIns.reload({where: getQueryParams(), page: {curr: _curr}});
    }

    $query.on('click', function () {
        reloadPage(1);
    });

    function getQueryParams() {
        return {
            businessType:'survey',
            accidentNo: $searchForm.find('input[name="accidentNo"]').val()?.trim(),
            accidentTitle: $searchForm.find('input[name="accidentTitle"]').val()?.trim(),
            accidentType: $searchForm.find("select[name='accidentType']").find("option:selected").val(),
            accidentLevel: $searchForm.find("select[name='accidentLevel']").find("option:selected").val(),
            startDate: $searchForm.find('input[name="startDate"]').val(),
            endDate: $searchForm.find('input[name="endDate"]').val(),
            tenantId: $searchForm.find("select[name='tenantSelect']").find("option:selected").val(),
            surveyStatus: $searchForm.find("select[name='surveyStatus']").find("option:selected").val(),
            obligationDeptId: $searchForm.find("select[name='obligationDeptId']").find("option:selected").val(),
            obligationUserId: $searchForm.find("select[name='obligationUserId']").find("option:selected").val(),
            invalidate_ie_cache: new Date()
        };
    }
    function getTableHeight() {
        return commonJS.calcTableHeight();
    }

    $(window).resize(function () {
        tableIns.reload({height: getTableHeight()});
    });
});